<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-document-copy" size="mini" @click="btnaddBrand">批量调整</el-button>
        <el-button type="primary" size="mini" @click="handleDownload">批量调整模板<i class="el-icon-paperclip el-icon--right"></i></el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="SN码" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="110" align="center" prop="admin_name" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="160" align="center" prop="value" label="SN码"></el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="firstJpushDate" label="上传日期" min-width="90" align="center">
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="firstActiveTime" label="激活日期" min-width="140" align="center">
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" prop="warrantyDate" label="理论库保" min-width="90" align="center">
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" prop="controlDate" label="管控期" min-width="90" align="center">
      </el-table-column>
      <el-table-column label="操作" min-width="80" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdActivationSn(scope.row.id)">编辑</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- SN激活管理 -->
    <el-dialog title="SN日期编辑" :visible.sync="editFormVisible" @close="editFormClose" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form :model="editForm" ref="ruleForm">
        <el-form-item label="激活管理:" label-width="100px" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保修期(月数):" label-width="100px" prop="warranty" style="width: 280px" v-show="editForm.type==1">
          <el-input v-model="editForm.warranty" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="管控期(月数):" label-width="100px"  prop="controlTime" style="width: 280px" v-show="editForm.type==2">
          <el-input v-model="editForm.controlTime" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="激活日期:" label-width="100px" prop="firstActiveTime" v-show="editForm.type==3">
          <div class="block">
            <el-date-picker
              v-model="editForm.firstActiveTime"
              type="date"
              format="yyyy 年 MM 月 dd 日"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="editSnTime('ruleForm')" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="SN日期管理" :visible.sync="batchFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form :model="batchForm" ref="batchForm" :rules="rules">
        <el-form-item label="日期管理:" label-width="100px" prop="type">
          <el-select v-model="batchForm.type" placeholder="请选择">
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="editSubjects">
          <el-form-item label="导入文件" label-width="100px" class="snElsx">
            <div class="">
              <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="batchForm.file.name"></el-input>
              <upload-excel-component class="flex mrg-top" :before-upload="batchUpload" @submitXlsx="submitXlsx"
                                      :loading="!videoFlag">
                <span>{{videoFlag ? '' : goodsData + '%'}}</span>
              </upload-excel-component>
            </div>
          </el-form-item>
          <div v-if="batchShow">
            <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ this.snData.success}}条
            </el-form-item>
            <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.err}}条
              {{ this.snData.errorCol.length >= 1 ? `( 位于:第${this.snData.errorCol.toString()}行 ), 只展示前10行` : ''}}
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-dialog>

    <!-- 导出start -->
    <el-dialog title="SN激活导出" :visible.sync="exporFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form :model="activeForm">
        <el-form-item label="导出类型:" label-width="130px">
          <el-radio-group v-model="activeForm.type">
            <el-radio :label="1">导出全部</el-radio>
            <el-radio :label="2">导出已激活</el-radio>
            <el-radio :label="3">导出未激活</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exporFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" size="mini" round @click="getexportActivationSn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 导出end -->
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryActivationSn, queryIdActivationSn, editActivationSn, importActivationSn, exportActivationSn } from "@/api/warranty.js";
import permission from '@/directive/permission/index.js' // 权限判断指令
import { mapState } from 'vuex'
import {batchEditSNTime, editSnTimeControl} from "@/api/warranty";
import mqttHandle from '@/utils/mqttHandler'
export default {
  components: { UploadExcelComponent, dynamicTable },
  directives: { permission },
  data() {
    return {
      checkboxVal: ["归属", "SN码", "激活时间", "管控到期时间"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "1", //搜索条件
      //编辑按钮控制
      editSubjects: true,
      subjectId: 0,
      listQuery: { startSize: 1, pageSize: 10, sn: undefined },
      editFormVisible: false,
      exporForm: { type: 1, file: {}, activationTime: '' },
      editForm: {type:1,warranty:0,controlTime:0,firstActiveTime:1672502400000, sn:''},
      batchForm: {type:1,file:{}},
      videoFlag: true,
      batchShow: false,
      snData: {},
      clearShow: true,
      exporFormVisible: false,
      batchFormVisible: false,
      activeForm: { type: 1, userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip") },
      options: [{label: '修改保修期', value:1},{label: '修改管控期', value: 2},{label: '修改激活时间', value: 3},{label:'清除激活时间', value: 4}],
      options2: [{label: '修改保修期', value:1},{label: '修改管控期', value: 2},{label:'清除激活时间', value: 4}],
      rules: {
        type: [{required: true, message: "请选择修改类型", trigger: "blur"}],
      },
      receiveNews: '',
    }
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getqueryActivationSn()
  },
  methods: {
    btnaddBrand() {
      this.editSubjects = true
      this.batchFormVisible = true
    },
    //根据ID获取信息
    getqueryIdActivationSn(id) {
      this.editSubjects = false
      this.editFormVisible = true
      this.subjectId = id
      queryIdActivationSn({ id: id }).then(({ data }) => {
        this.editForm.firstActiveTime = data.firstActiveTime == 0 ? 1672502400000 : data.firstActiveTime;
        this.editForm.controlTime = data.controlTime;
        this.editForm.sn = data.value;
        this.editForm.warranty = data.warranty
      }).catch(err => { })
    },
    //导出设备信息
    getexportActivationSn() {
      exportActivationSn(this.activeForm).then(res => {
        window.open('https://' + res.data.url)
      }).catch(err => {
        console.log('失败', err)
        err.code == 400 ? this.$message.error(err.msg) : ''
      })
    },
    //延长或清除change事件
    typeChange(val) {
      val == 1 ? this.clearShow = true : this.clearShow = false
    },
    submitXlsx(event) {
      var fd = new FormData()
      fd.append('file', this.batchForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('type', this.batchForm.type)
      this.videoFlag = false
      batchEditSNTime(fd).then(res => {
        this.snData = res.data
        this.batchShow = true
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getqueryActivationSn()
      }).catch(err => {
        this.videoFlag = true
      })
    },
    batchUpload(file) {
      this.batchForm.file = file
    },
    //导入确定事件
    uploadButton() {
      if (this.editSubjects) {
        if (this.exporForm.file instanceof File) {
          if (this.batchShow) {
            this.activeFormVisible = false
          } else {
            this.$message('存在导入文件未上传，请确认是否需要上传。')
          }
        } else {
          this.activeFormVisible = false
        }
      } else {
        console.log('编辑功能', this.subjectId)
        this.geteditActivationSn(this.subjectId)
      }
    },
    editSnTime(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let editForm = JSON.parse(JSON.stringify(this.editForm))
          editForm.last_ip = sessionStorage.getItem("Ip")
          editForm.userId = localStorage.getItem("ID")
          editForm.firstActiveTime /= 1000
          editSnTimeControl(editForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryActivationSn()
            this.editFormVisible = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });

    },
    //批次创立更新导入模板
    handleDownload() {
      let tHeader = ["SN码", "保修期/管控期(月数)"];
      let filterVal = ["sn", "time"];
      let list = [{ "sn": 'QNS2HBYS0009', "time": '3'}]
      import("@/vendor/Export2Excel").then(excel => {
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: '批量调整模板' });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    //修改设备激活信息
    geteditActivationSn(id) {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), type: this.exporForm.type, activationTime: this.exporForm.activationTime, id: id }
      console.log('参数', params)
      editActivationSn(params).then(res => {
        this.activeFormVisible = false
        this.$message.success(res.msg)
        this.getqueryActivationSn()
      }).catch(err => { })
    },
    addFormclose() {
      this.$nextTick(() => {
        this.batchForm = { type: 1, file: {}}
        this.clearShow = true
        this.videoFlag = true
        this.batchShow = false
      })
    },
    editFormClose() {
      this.$nextTick(() => {
        this.editForm = {type:1,warranty:0,controlTime:0,firstActiveTime:1672502400000, sn:''};
        this.editFormVisible = false;
      })
    },
    getqueryActivationSn() {
      queryActivationSn(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      });
    },
    //搜索,1:sn码,2,归属
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.sn = this.searchTable
          this.getqueryActivationSn();
          break;
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryActivationSn();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryActivationSn();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, sn: undefined }
      this.getqueryActivationSn()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
    /**创建mqtt**/
    createMqtt() {
      var mqtt; //mqtt 处理对象（全局变量）
      var client;
      var topicSends; //订阅的topic 例如：["Time1", "EngineMain1", "Console1", "Location1"]
      topicSends = ["Bob"]
      //创建链接，接收数据
      mqtt = new mqttHandle(topicSends);
      client = mqtt.createConnect();
      client.on("message", (topic, message) => {
        //数据分类
        try {
          this.receiveNews = this.receiveNews.concat(message);
          console.log('this is receiveNews', this.receiveNews)
          // this.realInfo(topic, this.receiveNews);
        } catch (error) {}
      });
    },

    //停止订阅mqtt
    disConnect() {
      var topicSends; //订阅的topic 例如：["Time1", "EngineMain1", "Console1", "Location1"]
      if (client != null) {
        client.unsubscribe(topicSends);
        client = null;
      }
    },

  },
  mounted() {
    // this.createMqtt();
  }
}
</script>
